package com.sun.androidexerciseproject.function.service;

import android.app.Notification;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;

import com.sun.androidexerciseproject.function.util.LogUtil;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Description:
 * File: NotificationMonitorService.java
 * Author: Administrator
 * Create: 2019/11/28 11:31
 */
public class NotificationMonitorService extends NotificationListenerService {
    private static final String TAG = "junfutong";

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        Notification notification = sbn.getNotification();
        Bundle extras = notification.extras;
        if (null != extras) {
            String pkgName = sbn.getPackageName();
            long when = notification.when;
            PendingIntent pendingIntent = notification.contentIntent;
            String intentStr = pendingIntent.toString();
            int hashCode = pendingIntent.hashCode();
            Class<?> cls = pendingIntent.getClass();
            try {
                Method method = cls.getMethod("getIntent");
                method.setAccessible(true);
                Intent intent = (Intent) method.invoke(pendingIntent);
                LogUtil.log(String.format("onNotificationPosted hashCode " + hashCode));
                String title = extras.getString(Notification.EXTRA_TITLE);
                String text = extras.getString(Notification.EXTRA_TEXT);
                LogUtil.log(String.format("onNotificationPosted pkgName = %s,title = %s,text = %s,intentStr = %s,when = %d", pkgName, title, text, intentStr, when));
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                LogUtil.log(String.format("onNotificationPosted exception  " + Log.getStackTraceString(e)));
            }
        }
    }
}
